import logging

import formencode
from tw.mods import pylonshf

from cibynet.lib.base import *
from cibynet.lib import gmail
from cibynet.lib.auth import authorisation
from cibynet.lib.utils import filter_dict
from cibynet.model import m_registrations
from cibynet.model.twforms import registration_form
from cibynet.model import utils as m_utils


log = logging.getLogger(__name__)


class RegistrationsController(BaseController):
  """REST Controller styled on the Atom Publishing Protocol"""

  @authorisation.UserInGroupD("admin")
  def index(self, format='html'):
    """GET /registrations: All items in the collection."""
    r_q = meta.Session.query(Registration)
    c.registrations_q = r_q
    return render("/registrations/index.mako")

  @pylonshf.validate(form=registration_form, error_handler="new")
  def create(self):
    """POST /registrations: Create a new item."""
    try:
      room = self.form_result.pop("room")
      user = User(**filter_dict(self.form_result, 
                  ['firstname', 'username', 'lastname', 'email',
                   'phonenumber']))
      machine = Machine(user, **filter_dict(self.form_result, 
                  ['macaddress', 'hostname']))
      check = Check(**filter_dict(self.form_result, 
                  ['bank', 'checknumber', 'checkissuer']))
      registration = Registration(check, user, room)
      meta.Session.add(registration)
      meta.Session.commit()
      if g.confirmation_email:
        msg = render("/registrations/confirmation_email.mako")
        gmail.send(msg, to=user, subject="[Cibynet] Registration confirmation")
      return "Registration created..." + str(self.form_result)
    except Exception, e:
      meta.Session.rollback()
      return "An error occured..." + str(e)

  def new(self, format='html'):
    """GET /registrations/new: Form to create a new item."""
    return render('/registrations/new.mako')

  def update(self, id):
    """PUT /registrations/id: Update an existing item."""
    pass

  def delete(self, id):
    """DELETE /registrations/id: Delete an existing item."""
    pass

  def show(self, id, format='html'):
    """GET /registrations/id: Show a specific item."""
    pass

  def edit(self, id, format='html'):
    """GET /registrations/id;edit: Form to edit an existing item."""
    pass

  def confirm(self, id):
    """ GET /registrations/id/confirm/?code=... to confirm the registration.
    """
    registration = m_utils.GetOneObject(Registration)
    if not registration:
      abort(404)
    authorisation.UserIs(registration.user)
    code = request.GET.get("code")
    if not code:
      return ("You must provide a confirmation code, please try to re-click on "
              "the provided link or copy/paste it in you browser...")
    if code != registration.confirmation_code:
      return ("Bad confirmation code. Try to copy/paste from your email to "
              "your browser to ensure all characters are present...")
    registration.confirm()
    return "Registration confirmed."
    